<?php

namespace app\controller;

use app\service\WorkbenchService;
use app\service\WorkbenchUserHistoryService;
use app\service\WorkbenchUserService;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class WorkbenchUserTaskController
{

    /**
     * @var WorkbenchService
     */
    private $workbenchUserService;

    public function __construct()
    {
        $this->workbenchUserService = new WorkbenchUserService();
    }

    /**
     * 数量统计
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function taskCount(Request $request): Response
    {
        $param = $request->post();
        $userIds = $param['user_id'] ?? [$request->getSaasUserId()];
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        $timeType = $param['time_type'] ?? 'plan_end_time';
        $projectId = $param['project_id'] ?? '';
        $returnData = [];
        if (!empty($param['history']) && $param['history'] == 'yes') {
            $res = WorkbenchUserHistoryService::getInstance()->taskCount($userIds, $startTime, $endTime, $timeType, $projectId);
        } else {
            $res = $this->workbenchUserService->taskCount($userIds, $startTime, $endTime, $timeType, $projectId);
        }
        $resMap = array_column($res, null, 'end_time');
        $yearMonthDayList = get_month_day_list($startTime, $endTime);
        foreach ($yearMonthDayList as $ymd) {
            $returnData[] = $resMap[$ymd] ?? ['number' => 0, 'end_time' => $ymd];
        }
        return json(success_response('', $returnData));
    }
}
